<?php
/**
 * Created by PhpStorm.
 * User: 12297
 * Date: 2018/5/29
 * Time: 0:14
 */
namespace app\api\service;

use app\admin\model\Integralrule;
use app\admin\model\Memberrule;
use app\admin\model\Membertype;
use app\api\controller\Integral;
use app\common\BaseHelper;
use app\common\model\Integralrecord;
use app\common\model\User;
use app\common\model\Useraccountdetails;
use app\common\model\Usermemberhistory;
use think\Db;
use think\Exception;
use think\Loader;

Loader::import('WxPay.WxPay',EXTEND_PATH,'.Api.php');

class RechargeNotify extends \WxPayNotify{
    public function NotifyProcess($data, &$msg){
        if($data['result_code'] == 'SUCCESS'){
            $orderNo = $data['out_trade_no'];
            $paytime = WxNotify::timeFormat($data['time_end']);
            Db::startTrans();
            try{
                $Useraccountdetails = Useraccountdetails::where('orderNO','=',$orderNo)->lock(true)->find();
                if($Useraccountdetails->rechargeStatus == 0){
                    $transaction_id = $data['transaction_id'];
                    Useraccountdetails::where('orderNO',$orderNo)->update(['transaction_id'=>$transaction_id,'payDate'=>$paytime,'rechargeStatus'=>1]);
                    //增加账户余额
                    $userid = $Useraccountdetails->userId;
                    if($Useraccountdetails->returnMoney){
                        $money = $Useraccountdetails->money + $Useraccountdetails->returnMoney;
                    }else{
                        $money = $Useraccountdetails->money;
                    }
                    User::where('id',$userid)->setInc('balance',$money);
                    if($Useraccountdetails->rechargeIntegral){
                        //增加积分
                        $rechargeIntegral = $Useraccountdetails->rechargeIntegral;
                        User::where('id',$userid)->setInc('integral',$rechargeIntegral);
                    }
                    //为当前用户开通的会员卡绑定历史规则（避免会员卡修改）
                    if($Useraccountdetails->record_type == Useraccountdetails::TYPE_3){
                        //开通会员成功需要做如下操作
                        //1.为用户绑定会员卡
                        //2.为当前用户开通的会员卡绑定历史规则（避免会员卡修改）
                        //3.如果赠送积分还需在积分记录表（integralrecord）增加记录
                        $membertype = Membertype::get($Useraccountdetails->memberId);
                        $memberrule = Memberrule::get($membertype->memRuleId);
                        $user = User::get($Useraccountdetails->userId);
                        $user->typeId = $membertype->id;
                        $user->memType = $membertype->memType;
                        $user->isMember = 2;
                        if($membertype->endTime!=0){
                            $user->memberendtime = time()+$membertype->endTime;
                        }else{
                            $user->memberendtime = 0;
                        }
                        $user->save();
                        $this->inssertHistoryMemberRule($user->id,$membertype,$memberrule);

                        if($memberrule->openStatus == 1 && $Useraccountdetails->rechargeIntegral>0){
                            $Integral = new Integral();
                            $Integral->insertRecordCz($Useraccountdetails,Integralrecord::TYPE_6,$Useraccountdetails->rechargeIntegral);
                        }
                    }elseif ($Useraccountdetails->record_type == Useraccountdetails::TYPE_1){
                        //如果是充值要判断是否送积分
                        $tenantId = $Useraccountdetails->tenantId;
                        $Integralrule = Integralrule::where('tenantId',$tenantId)->find();
                        if($Integralrule){
                            if($Integralrule->integralNum > 0){
                                User::where('id',$Useraccountdetails->userId)->setInc('integral',$Integralrule->integralNum);
                                //插入记录
                                $Integral = new Integral();
                                $Integral->insertRecordCz($Useraccountdetails,Integralrecord::TYPE_7,$Integralrule->integralNum);
                            }
                        }
                    }
                }

                Db::commit();
                return true;
            }catch (Exception $ex){
                Db::rollback();
                return false;
            }

        }else{
            return true;
        }
    }

    /**
     * 为当前用户开通的会员卡绑定历史规则（避免会员卡修改）
     * @param $userId
     * @param $membertype
     * @param $memberrule
     */
    private function inssertHistoryMemberRule($userId,$membertype,$memberrule){
        $Usermemberhistory = new Usermemberhistory();
        $history = $Usermemberhistory->where('userId',$userId)->find();
        if($history){
            $history->memType = $membertype->memType;
            $history->openCondition = $memberrule->openStatus;
            $history->endTime = $membertype->endTime;
            $history->term = $membertype->term;
            $history->timetype = $membertype->timetype;
            $history->tenantId = $membertype->tenantId;
            $history->rechargeOpenMoney = $memberrule->rechargeOpenMoney;
            $history->returnMoney = $memberrule->returnMoney;
            $history->rechargeIntegral = $memberrule->rechargeIntegral;
            $history->isMemBerShop = $memberrule->isMemBerShop;
            $history->memberDiscounts = $memberrule->memberDiscounts;
            $history->consumeMoney = $memberrule->consumeMoney;
            $history->consumeIntegral = $memberrule->consumeIntegral;
            $history->save();
        }else{
            $Usermemberhistory->id = BaseHelper::getUUID();
            $Usermemberhistory->userId = $userId;
            $Usermemberhistory->membertype_id = $membertype->id;
            $Usermemberhistory->memType = $membertype->memType;
            $Usermemberhistory->openCondition = $memberrule->openStatus;
            $Usermemberhistory->endTime = $membertype->endTime;
            $Usermemberhistory->term = $membertype->term;
            $Usermemberhistory->timetype = $membertype->timetype;
            $Usermemberhistory->tenantId = $membertype->tenantId;
            $Usermemberhistory->rechargeOpenMoney = $memberrule->rechargeOpenMoney;
            $Usermemberhistory->returnMoney = $memberrule->returnMoney;
            $Usermemberhistory->rechargeIntegral = $memberrule->rechargeIntegral;
            $Usermemberhistory->isMemBerShop = $memberrule->isMemBerShop;
            $Usermemberhistory->memberDiscounts = $memberrule->memberDiscounts;
            $Usermemberhistory->consumeMoney = $memberrule->consumeMoney;
            $Usermemberhistory->consumeIntegral = $memberrule->consumeIntegral;
            $Usermemberhistory->save();
        }


    }
}